<!--
 * @Author: OBKoro1
 * @Date: 2022-03-07 10:29:45
 * @LastEditors: yangyongtao
 * @LastEditTime: 2023-12-04 10:12:53
 * @FilePath: \onemodeSWJ\src\views\paramPlanManage\sedParamDataManage\sedParamDataAddSX.vue
 * @Description: 
 * 
 * Copyright (c) 2022 by 用户/公司名, All Rights Reserved. 
-->
<template>
  <el-table
    style="margin: 10px 0; width: 50%"
    :data="sedData"
    border
    stripe
    size="small"
    @cell-mouse-leave="onMouseleave"
    @row-dblclick="onDblclick"
  >
    <el-table-column prop="dataName" align="center" label="断面名" />

    <el-table-column
      v-for="item in columns"
      :key="item.dataIndex"
      :label="item.title"
      :width="item.width"
      align="center"
    >
      <template #default="scope">
        <div v-if="item.title != ''">
          <el-input
            v-if="editableData[scope.row.dataName][item.dataIndex]"
            v-model="editableData[scope.row.dataName][item.dataIndex]"
            style="margin: -5px 0; text-align: center"
            type="number"
          />
          <div :data-type="item.dataIndex" v-else>
            {{ scope.row[item.dataIndex] }}
          </div>
        </div>
        <div v-else>
          <el-button
            style="padding-left: 8px"
            type="danger"
            size="small"
            text
            @click.prevent="deleteSedParamData(scope.row.dataName)"
          >
            <CloseOutlined />
          </el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <div>
    <el-button style="width: 50%" text @click="addSedParamData">
      <PlusOutlined />
    </el-button>
  </div>

  <div>
    <el-button
      style="
        position: relative;
        left: 25%;
        transform: translateX(-48%);
        margin-top: 50px;
      "
      type="primary"
      :loading="submitBtnLoadingType"
      @click="submit"
    >
      方案保存
    </el-button>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  provide,
  watch,
  inject,
  reactive,
  toRefs,
  onMounted,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { cloneDeep } from "lodash-es";
import { ElMessage, ElMessageBox } from "element-plus";
import { CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";

import {
  searchNsArgumentsType,
  addNSTypeArguments,
  sectionNameVerify,
} from "@/request/api";

export default defineComponent({
  components: {
    CloseOutlined,
    PlusOutlined,
  },
  setup() {
    const store = useStore();
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      // 方案参数
      planData: {},
      planType: null,

      // 泥沙参数表格编辑参数
      editableData: {},
      // 泥沙参数数据
      sedData: [],
      // 泥沙参数表头数据
      columns: [],

      // 提交按钮加载状态
      submitBtnLoadingType: false,
    });

    onMounted(() => {
      state.planData = route.params;
      state.planType = route.params.type;

      getNsArgumentsList();
    });

    /**
     * @description: 获取泥沙参数
     * @return {*}
     */
    function getNsArgumentsList() {
      searchNsArgumentsType({
        id: route.params.id,
        reservoir: route.params.reservoir,
        river: route.params.river,
        type: route.params.type,
        Fatype: "fa",
      }).then((res: any) => {
        // 处理返回JSON字符串数据 以表格数据形式存储
        state.editableData = {};

        res[state.planType].forEach((item) => {
          let obj = {
            dataName: "",
          };

          item.split(",").forEach((ele, i) => {
            if (i === 0) {
              obj.dataName = ele;
              state.editableData[ele] = {};
            } else {
              obj["param" + i] = ele.trim();
            }
          });

          state.sedData.push(obj);
        });

        switch (route.params.type) {
          case "csps":
            state.columns = [
              {
                title: "0.008",
                dataIndex: "param1",
              },
              {
                title: "0.031",
                dataIndex: "param2",
              },
              {
                title: "0.125",
                dataIndex: "param3",
              },
              {
                title: "1",
                dataIndex: "param4",
              },
              {
                title: "4",
                dataIndex: "param5",
              },
              {
                title: "32",
                dataIndex: "param6",
              },
              {
                title: "250",
                dataIndex: "param7",
              },
            ];
            break;
          case "csgds":
            state.columns = [
              // 1
              {
                title: "干容重",
                dataIndex: "param1",
              },
            ];
            break;
          case "eds":
            state.columns = [
              // 2
              {
                title: "e值",
                dataIndex: "param1",
              },
              {
                title: "d值",
                dataIndex: "param2",
              },
              {
                title: "m值",
                dataIndex: "param3",
              },
            ];
            break;
          case "kms":
            state.columns = [
              // 2
              {
                title: "k值",
                dataIndex: "param1",
              },
              {
                title: "m值",
                dataIndex: "param2",
              },
            ];
            break;
        }
      });
    }

    /**
     * @description: 鼠标双击表格事件
     * @param dataName 当前行断面名
     * @param event 鼠标双击单元格
     * @return {*}
     */
    function onDblclick({ dataName, key }, cell, event) {
      const type = event.target.getAttribute("data-type");

      if (type && type.includes("param")) {
        state.editableData[dataName][type] = cloneDeep(
          state.sedData.find((item) => item.dataName == dataName)[type]
        );
      }
    }

    /**
     * @description: 鼠标移出单元格事件
     * @param dataName 当前行断面名
     * @return {*}
     */
    function onMouseleave({ dataName, key }) {
      Object.assign(
        state.sedData.filter((item) => item.dataName == dataName)[0],
        state.editableData[dataName]
      );

      state.editableData[dataName] = {};
    }

    /**
     * @description: 新增断面信息
     * @return {*}
     */
    function addSedParamData() {
      ElMessageBox.prompt("请输入断面名称", "新增断面", {
        confirmButtonText: "新增",
        cancelButtonText: "取消",
      }).then(({ value }) => {
        let obj = cloneDeep(state.sedData[0]);

        for (const key in obj) {
          obj[key] = "0";
        }
        obj.dataName = value;

        sectionNameVerify({ xscd: value }).then((res: any) => {
          if (res.code === "1") {
            state.editableData[value] = {};

            state.sedData.push(obj);
          } else {
            ElMessage.error(
              "断面名称字母需要大写或者所输入断面不存在，请确认所输入断面名称是否正确"
            );
          }
        });
      });
    }

    /**
     * @description: 删除断面信息
     * @param dataName 当前行断面名
     * @return {*}
     */
    function deleteSedParamData(dataName) {
      state.sedData = state.sedData.filter((item) => item.dataName != dataName);
    }

    /**
     * @description: 根据type返回不同类型
     * @param text 不同的type
     * @return {*}
     */
    function labelText(text) {
      switch (text) {
        case "kms":
          return "挟沙力系数";
        case "eds":
          return "冲淤系数";
        case "csps":
          return "床沙级配";
        case "csgds":
          return "床沙粒径";
      }
    }

    /**
     * @description: 保存方案
     * @return {*}
     */
    function submit() {
      // 提交按钮修改为加载状态
      state.submitBtnLoadingType = true;

      // 将表格数据处理为接口需要数据
      let arr = [];

      state.sedData.forEach((item) => {
        delete item.key;

        arr.push(
          Object.getOwnPropertyNames(item)
            .map((i) => item[i])
            .join(",")
        );
      });

      // 保存当前数据
      addNSTypeArguments({
        ...state.planData,
        data: JSON.stringify({
          [state.planType]: arr,
        }),
      }).then((res: any) => {
        // 提交按钮取消加载状态
        state.submitBtnLoadingType = false;

        if (res.code == 1) {
          ElMessage.success(res.msg);

          setTimeout(() => {
            router.push({
              path: "sedParamDataList",
              query: {
                type: route.params.type,
              },
            });
          }, 1000);
        } else {
          ElMessage.error(res.msg);
        }
      });
    }

    return {
      ...toRefs(state),

      getNsArgumentsList,
      onDblclick,
      onMouseleave,
      addSedParamData,
      deleteSedParamData,
      labelText,
      submit,
    };
  },
});
</script>

<style scoped lang="less">
.sedFormInput {
  margin-bottom: 20px;
  .form-box {
    display: flex;
  }
  .el-input {
    width: 100px;
    margin: 0 4px 8px 0;
  }
}
</style>
